package com.neusoft.elm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.neusoft.elm.po.Cart;
import com.neusoft.elm.service.CartService;
import com.neusoft.elm.service.impl.CartServiceImpl;

@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        
        PrintWriter out = response.getWriter();
        
        try {
            String action = request.getParameter("action");
            CartService cartService = new CartServiceImpl();
            
            if ("add".equals(action)) {
                // 添加商品到购物车
                addToCart(request, response, cartService, out);
            } else if ("remove".equals(action)) {
                // 从购物车移除商品
                removeFromCart(request, response, cartService, out);
            } else if ("update".equals(action)) {
                // 更新购物车商品数量
                updateCart(request, response, cartService, out);
            } else if ("list".equals(action)) {
                // 获取购物车列表
                getCartList(request, response, cartService, out);
            } else if ("clear".equals(action)) {
                // 清空购物车
                clearCart(request, response, cartService, out);
            } else {
                out.print("{\"success\":false,\"message\":\"无效的操作类型\"}");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"操作失败: " + e.getMessage() + "\"}");
        } finally {
            out.close();
        }
    }
    
    private void addToCart(HttpServletRequest request, HttpServletResponse response, 
                          CartService cartService, PrintWriter out) throws Exception {
        String userId = request.getParameter("userId");
        String foodIdStr = request.getParameter("foodId");
        String businessIdStr = request.getParameter("businessId");
        
        if (userId == null || foodIdStr == null || businessIdStr == null) {
            out.print("{\"success\":false,\"message\":\"参数不完整\"}");
            return;
        }
        
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setFoodId(Integer.valueOf(foodIdStr));
        cart.setBusinessId(Integer.valueOf(businessIdStr));
        
        int result = cartService.saveCart(cart);
        
        if (result > 0) {
            out.print("{\"success\":true,\"message\":\"添加成功\"}");
        } else {
            out.print("{\"success\":false,\"message\":\"添加失败\"}");
        }
    }
    
    private void removeFromCart(HttpServletRequest request, HttpServletResponse response, 
                               CartService cartService, PrintWriter out) throws Exception {
        String userId = request.getParameter("userId");
        String foodIdStr = request.getParameter("foodId");
        String businessIdStr = request.getParameter("businessId");
        
        if (userId == null || foodIdStr == null || businessIdStr == null) {
            out.print("{\"success\":false,\"message\":\"参数不完整\"}");
            return;
        }
        
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setFoodId(Integer.valueOf(foodIdStr));
        cart.setBusinessId(Integer.valueOf(businessIdStr));
        
        int result = cartService.removeCart(cart);
        
        if (result > 0) {
            out.print("{\"success\":true,\"message\":\"移除成功\"}");
        } else {
            out.print("{\"success\":false,\"message\":\"移除失败\"}");
        }
    }
    
    private void updateCart(HttpServletRequest request, HttpServletResponse response, 
                           CartService cartService, PrintWriter out) throws Exception {
        String userId = request.getParameter("userId");
        String foodIdStr = request.getParameter("foodId");
        String businessIdStr = request.getParameter("businessId");
        String quantityStr = request.getParameter("quantity");
        
        if (userId == null || foodIdStr == null || businessIdStr == null || quantityStr == null) {
            out.print("{\"success\":false,\"message\":\"参数不完整\"}");
            return;
        }
        
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setFoodId(Integer.valueOf(foodIdStr));
        cart.setBusinessId(Integer.valueOf(businessIdStr));
        cart.setQuantity(Integer.valueOf(quantityStr));
        
        int result = cartService.updateCart(cart);
        
        if (result > 0) {
            out.print("{\"success\":true,\"message\":\"更新成功\"}");
        } else {
            out.print("{\"success\":false,\"message\":\"更新失败\"}");
        }
    }
    
    private void getCartList(HttpServletRequest request, HttpServletResponse response, 
                            CartService cartService, PrintWriter out) throws Exception {
        String userId = request.getParameter("userId");
        String businessIdStr = request.getParameter("businessId");
        
        if (userId == null) {
            out.print("{\"success\":false,\"message\":\"用户ID不能为空\"}");
            return;
        }
        
        Cart cart = new Cart();
        cart.setUserId(userId);
        if (businessIdStr != null && !businessIdStr.trim().isEmpty()) {
            cart.setBusinessId(Integer.valueOf(businessIdStr));
        }
        
        List<Cart> cartList = cartService.listCart(cart);
        
        Gson gson = new Gson();
        String jsonResult = gson.toJson(cartList);
        out.print(jsonResult);
    }
    
    private void clearCart(HttpServletRequest request, HttpServletResponse response, 
                          CartService cartService, PrintWriter out) throws Exception {
        String userId = request.getParameter("userId");
        String businessIdStr = request.getParameter("businessId");
        
        if (userId == null || businessIdStr == null) {
            out.print("{\"success\":false,\"message\":\"参数不完整\"}");
            return;
        }
        
        // 这里需要在CartService中添加clearCart方法
        // 暂时使用现有方法实现
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setBusinessId(Integer.valueOf(businessIdStr));
        
        List<Cart> cartList = cartService.listCart(cart);
        int successCount = 0;
        
        for (Cart item : cartList) {
            int result = cartService.removeCart(item);
            if (result > 0) {
                successCount++;
            }
        }
        
        if (successCount == cartList.size()) {
            out.print("{\"success\":true,\"message\":\"清空购物车成功\"}");
        } else {
            out.print("{\"success\":false,\"message\":\"清空购物车失败\"}");
        }
    }
}